#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QDebug>
#include <cmark.h> // CommonMark 头文件
#include <QScrollBar>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow)
{


    ui->setupUi(this);

    deepSeekAPI = new DeepSeekAPI(this);
    connect(deepSeekAPI, &DeepSeekAPI::responseFinished, this, QOverload<const QString &>::of(&MainWindow::onResponseReceived));
    connect(deepSeekAPI, &DeepSeekAPI::responseReceived, this, QOverload<const QString &,const QString &>::of(&MainWindow::onResponseReceived));
    connect(deepSeekAPI, &DeepSeekAPI::streamResponseStarted, this, &MainWindow::onStreamResponseStarted);
    connect(deepSeekAPI, &DeepSeekAPI::streamResponseReasoningContent, this, &MainWindow::onStreamResponseReasoningContent);
    connect(deepSeekAPI, &DeepSeekAPI::streamResponseReceived, this, &MainWindow::onStreamResponseReceived);

    ollamaAPI = new OllamaAPI(this);
    connect(ollamaAPI, &OllamaAPI::responseFinished, this, QOverload<const QString &>::of(&MainWindow::onResponseReceived));
    connect(ollamaAPI, &OllamaAPI::responseReceived, this, QOverload<const QString &,const QString &>::of(&MainWindow::onResponseReceived));
    connect(ollamaAPI, &OllamaAPI::streamResponseStarted, this, &MainWindow::onStreamResponseStarted);
    connect(ollamaAPI, &OllamaAPI::streamResponseReasoningContent, this, &MainWindow::onStreamResponseReasoningContent);
    connect(ollamaAPI, &OllamaAPI::streamResponseReceived, this, &MainWindow::onStreamResponseReceived);

    // 连接按钮点击信号
    connect(ui->newConversationButton, &QPushButton::clicked, this, &MainWindow::newConversation);
    connect(ui->tabWidget, &QTabWidget::tabCloseRequested, this, &MainWindow::closeConversation);

    connect(ui->sendButton, &QPushButton::clicked, this, &MainWindow::sendMessage);

    ui->tabWidget->widget(0)->setProperty("conversationId",DeepSeekAPI::s_Id++);
    ui->tabWidget->widget(0)->setProperty("conversationId",OllamaAPI::s_Id++);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::sendMessage()
{
    // 获取当前标签页
    QWidget *currentTab = ui->tabWidget->currentWidget();
    if (!currentTab) return;

    // 获取输入框
    QLineEdit *input = currentTab->findChild<QLineEdit *>("inputLineEdit");
    if (!input) return;

    // 获取预览框
    QTextBrowser *preview = currentTab->findChild<QTextBrowser *>("previewBrowser");
    if (!preview) return;

    // 获取用户输入的消息
    QString message = input->text();
    if (message.isEmpty()) return;

    // 获取当前对话的 ID
    QString conversationId = currentTab->property("conversationId").toString();

    // 将用户消息以 Markdown 格式添加到对话历史，并添加换行符
    input->clear();
    m_mapMsg[conversationId] += "**You:** " + message + "\n\n";
    QString html = renderMarkdown(m_mapMsg[conversationId]);
    preview->setHtml(html);

    // 发送消息到 DeepSeek API
    ollamaAPI->sendRequest(message, conversationId);
}

void MainWindow::newConversation()
{
    // 创建一个新的标签页
    QWidget *tab = new QWidget();
    QVBoxLayout *layout = new QVBoxLayout(tab);

    // 创建 Markdown 预览框
    QTextBrowser *preview = new QTextBrowser(tab);
    preview->setObjectName("previewBrowser"); // 设置对象名称
    preview->setOpenLinks(false); // 禁用链接跳转
    layout->addWidget(preview);

    // 创建输入框和发送按钮
    QWidget *inputWidget = new QWidget(tab);
    QHBoxLayout *inputLayout = new QHBoxLayout(inputWidget);

    QLineEdit *input = new QLineEdit(inputWidget);
    input->setObjectName("inputLineEdit"); // 设置对象名称
    connect(input, &QLineEdit::returnPressed, this, &MainWindow::sendMessage); // 回车发送消息
    inputLayout->addWidget(input);

    QPushButton *sendButton = new QPushButton("Send", inputWidget);
    connect(sendButton, &QPushButton::clicked, this, &MainWindow::sendMessage);
    inputLayout->addWidget(sendButton);

    layout->addWidget(inputWidget);

    tab->setProperty("conversationId",DeepSeekAPI::s_Id++);
    // 将新标签页添加到 QTabWidget
    int index = ui->tabWidget->addTab(tab, QString("Conversation %1").arg(ui->tabWidget->count() + 1));
    ui->tabWidget->setCurrentIndex(index);
}

void MainWindow::closeConversation(int index)
{
    // 关闭指定索引的标签页
    QWidget *tab = ui->tabWidget->widget(index);
    if (tab) {
        ui->tabWidget->removeTab(index);
        delete tab;
    }
}

QString MainWindow::renderMarkdown(const QString &markdown)
{
    // 使用 CommonMark 将 Markdown 转换为 HTML
    QByteArray markdownData = markdown.toUtf8();
    char *html = cmark_markdown_to_html(markdownData.constData(), markdownData.size(), CMARK_OPT_DEFAULT);
    QString result = QString::fromUtf8(html);
    free(html);
    return result;
}

void MainWindow::onResponseReceived(const QString &response, const QString &conversationId)
{
    // 获取当前标签页
    QWidget *currentTab = ui->tabWidget->currentWidget();
    if (!currentTab) return;

    // 获取预览框
    QTextBrowser *preview = currentTab->findChild<QTextBrowser *>("previewBrowser");
    if (!preview) return;

    // 将 API 响应添加到 Markdown 输入框
    m_mapMsg[conversationId] += "**DeepSeek:** " + response + "\n\n";

    QString html = renderMarkdown(m_mapMsg[conversationId]);
    preview->setHtml(html);
}

void MainWindow::onResponseReceived(const QString &conversationId)
{
    m_mapMsg[conversationId] += "\n\n";
}

void MainWindow::onStreamResponseStarted(const QString &chunk, const QString &conversationId)
{
    m_mapMsg[conversationId] += "**DeepSeek:** ";
}

void MainWindow::onStreamResponseReasoningContent(const QString &chunk, const QString &conversationId)
{
    // 获取当前标签页
    QWidget *currentTab = ui->tabWidget->currentWidget();
    if (!currentTab) return;

    // 获取预览框
    QTextBrowser *preview = currentTab->findChild<QTextBrowser *>("previewBrowser");
    if (!preview) return;

    m_mapMsg[conversationId] += chunk;

    QString html = renderMarkdown(m_mapMsg[conversationId]);
    preview->setHtml(html);

    QScrollBar *scrollBar = preview->verticalScrollBar();
    scrollBar->setValue(scrollBar->maximum());
}

void MainWindow::onStreamResponseReceived(const QString &chunk, const QString &conversationId)
{
    // 获取当前标签页
    QWidget *currentTab = ui->tabWidget->currentWidget();
    if (!currentTab) return;

    // 获取预览框
    QTextBrowser *preview = currentTab->findChild<QTextBrowser *>("previewBrowser");
    if (!preview) return;

    m_mapMsg[conversationId] += chunk;

    QString html = renderMarkdown(m_mapMsg[conversationId]);
    preview->setHtml(html);

    QScrollBar *scrollBar = preview->verticalScrollBar();
    scrollBar->setValue(scrollBar->maximum());
}
